package com.udi.common.utils.poi;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.udi.common.exception.BusinessException;
import com.udi.framework.aspectj.lang.annotation.Excel;
import com.udi.framework.config.udiConfig;
import com.udi.framework.web.domain.AjaxResult;
import com.udi.project.business.utils.excel.daomain.LogoExcel;
import com.udi.project.business.utils.excel.daomain.deviceClinicalExcel;
import com.udi.project.business.utils.excel.daomain.devicePackageExcel;
import com.udi.project.business.utils.excel.daomain.deviceStorageExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.List;

@Slf4j
public class Excels {

    /**
     * excel表名
     */
    private String excelName;
    /**
     * 工作薄对象
     */
    private Workbook wb;
    /**
     * 导出数据
     */
    private JSONArray array;
    /**
     * 导出类型（EXPORT:导出数据；IMPORT：导入模板）
     */
    private Excel.Type type;

    public AjaxResult export(JSONArray array, String excelName){

        this.init(array,excelName, Excel.Type.EXPORT);
        return exportExcel();
    }

    /**
     * 初始化一个工作簿
     * */
    public void init(JSONArray array, String excelName, Excel.Type type) {

        this.array = array;
        this.excelName = excelName;
        this.type = type;
        createWorkbook();
    }

    /**
     * 创建一个工作簿
     */
    public void createWorkbook()
    {
        this.wb = new SXSSFWorkbook(500);
    }

    /**
     * 对list数据源将其里面的数据导入到excel表单
     *
     * @return 结果
     */
    public AjaxResult exportExcel() {
        OutputStream out = null;
        try {
            // 取出一共有多少个sheet.
            double sheetNo = array.size();
            //加载各个表数据
            for (int i = 0; i < sheetNo; i++) {
                if(((JSONObject)array.get(i)).get("list1") != null){

                    ExcelUtils<LogoExcel> excelUtil = new ExcelUtils<>(LogoExcel.class);
                    List<LogoExcel> list = (List<LogoExcel>) ((JSONObject)array.get(i)).get("list1");
                    String name =  ((JSONObject)array.get(i)).getString("name");
                    excelUtil.exportExcel(list,name,wb,i);

                }else if(((JSONObject)array.get(i)).get("list2") != null){

                    ExcelUtils<devicePackageExcel> excelUtil = new ExcelUtils<>(devicePackageExcel.class);
                    List<devicePackageExcel> list = (List<devicePackageExcel>) ((JSONObject)array.get(i)).get("list2");
                    String name =  ((JSONObject)array.get(i)).getString("name");
                    excelUtil.exportExcel(list,name,wb,i);

                }else if(((JSONObject)array.get(i)).get("list3") != null){

                    ExcelUtils<deviceStorageExcel> excelUtil = new ExcelUtils<>(deviceStorageExcel.class);
                    List<deviceStorageExcel> list = (List<deviceStorageExcel>) ((JSONObject)array.get(i)).get("list3");
                    String name =  ((JSONObject)array.get(i)).getString("name");
                    excelUtil.exportExcel(list,name,wb,i);

                }else if(((JSONObject)array.get(i)).get("list4") != null){

                    ExcelUtils<deviceClinicalExcel> excelUtil = new ExcelUtils<>(deviceClinicalExcel.class);
                    List<deviceClinicalExcel> list1 = (List<deviceClinicalExcel>) ((JSONObject)array.get(i)).get("list4");
                    String name =  ((JSONObject)array.get(i)).getString("name");
                    excelUtil.exportExcel(list1,name,wb,i);
                }
            }
            //输出文件
            String filename = encodingFilename(excelName);
            out = new FileOutputStream(getAbsoluteFile(filename));
            wb.write(out);
            return AjaxResult.success(filename);
        } catch (Exception e) {
            log.error("导出Excel异常{}", e.getMessage());
            throw new BusinessException("导出Excel失败，请联系网站管理员！");
        } finally {
            if (wb != null) {
                try
                {
                    wb.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        }
    }
    /**
     * 编码文件名
     */
    public String encodingFilename(String filename) {
        filename = filename + ".xlsx";
        return filename;
    }

    /**
     * 获取下载路径
     *
     * @param filename 文件名称
     */
    public String getAbsoluteFile(String filename) {
        String downloadPath = udiConfig.getDownloadPath() + filename;
        File desc = new File(downloadPath);
        if (!desc.getParentFile().exists())
        {
            desc.getParentFile().mkdirs();
        }
        return downloadPath;
    }
}
